﻿using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using HslCommunicationDemo;
using HslCommunication.Profinet.Siemens;
using HslCommunication.Core.Pipe;
using HslCommunication;
using HslCommunication.Core.Device;
using HslCommunication.ModBus;
using HslCommunication.MQTT;
using Microsoft.AspNet.SignalR.Client;
using HslCommunication.Profinet.XINJE;
using Syntec.Remote;
using System.Net.NetworkInformation;

namespace DataCollectService
{
    [HubName("DataCollectHub")]
    public class DataCollectHub : Hub
    {
        static List<DeviceConfig> listDeviceConfig = new List<DeviceConfig>();
        static List<Thread> listTasks = new List<Thread>();
        static List<Protocol> listDBConfig = new List<Protocol>();
        static DataInterfaceHelper dataInterfaceHelper;
        static string ServiceIP;
        static HubConnection serviceHubConnection;
        static IHubProxy serverHub;
        static SQLiteHelper sqlLiteHelper;

        #region 公共做Server端进程控制
        //MQTT服务端数组对象
        static Dictionary<MqttServer, List<DeviceConfig>> listMqttServer = new Dictionary<MqttServer, List<DeviceConfig>>();
        //Syntec数组循环对象
        static Dictionary<DeviceConfig, SyntecRemoteCNC> listSyntec = new Dictionary<DeviceConfig, SyntecRemoteCNC>();
        static bool isStartSyntecService = false;
        #endregion



        /// <summary>
        /// 初始化所有设备采集配置
        /// </summary>
        public void InitDeviceCollectConfig(string _deviceConfigStr, string _protocalStr, string _serviceIP)
        {
            try
            {
                //Log.SaveNote("获取到设备协议:" + _deviceConfigStr + ";" + _protocalStr);
                listDeviceConfig = _deviceConfigStr.FromJSON<List<DeviceConfig>>();
                Dictionary<string, string> deviceProtocol = new Dictionary<string, string>();
                sqlLiteHelper = new SQLiteHelper("CJ.db");

                List<DeviceConfig> listCacheDeviceConfig = null;
                string cacheConfig = ReadTodayDeviceRunStatus();
                if (cacheConfig != "")
                {
                    try
                    {
                        listCacheDeviceConfig = cacheConfig.FromJSON<List<DeviceConfig>>();
                    }
                    catch (Exception ex)
                    {
                        //数据无法转换为json格式
                        listCacheDeviceConfig = null;
                        //清空数据
                        RecordDeviceRunStatus("");
                    }
                }
                //循环设备列表
                foreach (var deviceObj in listDeviceConfig)
                {
                    deviceObj.IsRunning = false;
                    deviceObj.RunStatus = 0;
                    deviceObj.LastCJTime = DateTime.Now;
                    if (listCacheDeviceConfig != null)
                    {
                        var cacheDevice = listCacheDeviceConfig.Where(x => x.DeviceID == deviceObj.DeviceID).FirstOrDefault();
                        if (cacheDevice != null)
                        {
                            deviceObj.RunTime = cacheDevice.RunTime;
                            deviceObj.StopTime = cacheDevice.StopTime;
                            deviceObj.WaitTime = cacheDevice.WaitTime;
                            deviceObj.WarningTime = cacheDevice.WarningTime;
                        }
                    }
                    deviceProtocol.Add(deviceObj.DeviceID.ToString(), deviceObj.DataBaseConfig);
                }
                //设置协议配置对象
                dataInterfaceHelper = new DataInterfaceHelper(deviceProtocol);
                dataInterfaceHelper.listProtocal = _protocalStr.FromJSON<List<Protocol>>();
                ServiceIP = _serviceIP;
                InitServerConnection();
                //开启循环返回设备状态
                GetAllDeviceStatus();
            }
            catch (Exception ex)
            {
                Log.SaveNote("初始化设备协议失败:" + ex.ToString());
            }
        }
        /// <summary>
        /// 开启全部采集设备配置
        /// </summary>
        public void PlayAllDeviceCollect()
        {
            //终止当前所有运行线程
            foreach (var task in listTasks)
            {
                task.Abort();
            }
            listTasks.Clear();
            foreach (var deviceObj in listDeviceConfig)
            {
                Thread threadDevice = new Thread(() =>
                {
                    PlayDeviceCollect(deviceObj);
                });
                threadDevice.Name = deviceObj.DeviceNo;
                threadDevice.Start();
                listTasks.Add(threadDevice);
                Thread.Sleep(2000);
            }
        }
        /// <summary>
        /// 开启单个采集设备配置
        /// </summary>
        /// <param name="deviceNo"></param>
        public void PlaySingleDeviceCollect(string deviceID)
        {
            //终止当前所有运行线程
            foreach (var task in listTasks)
            {
                if (task.Name == deviceID)
                {
                    task.Abort();
                    listTasks.Remove(task);
                    break;
                }
            }
            foreach (var deviceObj in listDeviceConfig)
            {
                if (deviceObj.DeviceID.ToString() == deviceID)
                {
                    Thread threadDevice = new Thread(() =>
                    {
                        PlayDeviceCollect(deviceObj);
                    });
                    threadDevice.Name = deviceObj.DeviceID.ToString();
                    threadDevice.Start();
                    listTasks.Add(threadDevice);
                }
            }
        }

        /// <summary>
        /// 停止全部采集设备配置
        /// </summary>
        public void StopAllDeviceCollect()
        {
            //终止当前所有运行线程
            foreach (var task in listTasks)
            {
                task.Abort();
            }
            listTasks.Clear();

            foreach (var deviceConfig in listDeviceConfig)
            {
                deviceConfig.IsRunning = false;
                deviceConfig.RunStatus = 0;
            }
        }
        /// <summary>
        /// 暂停单个采集设备配置
        /// </summary>
        /// <param name="deviceNo"></param>
        public void StopSingleDeviceCollect(string deviceID)
        {
            //终止当前所有运行线程
            foreach (var task in listTasks)
            {
                if (task.Name == deviceID)
                {
                    task.Abort();
                    listTasks.Remove(task);
                    break;
                }
            }
            var deviceConfig = listDeviceConfig.Where(x => x.DeviceID.ToString() == deviceID).FirstOrDefault();
            if (deviceConfig != null)
            {
                deviceConfig.IsRunning = false;
                deviceConfig.RunStatus = 0;
            }
        }


        public void PlayDeviceCollect(DeviceConfig deviceConfig)
        {
            try
            {
                //配置信息如果不为空
                if (!string.IsNullOrEmpty(deviceConfig.ProtocalConfig))
                {
                    ProtocalInfo protocalInfo = deviceConfig.ProtocalConfig.FromJSON<ProtocalInfo>();
                    //此部分逐一枚举，按实际项目来增加协议要求
                    #region 西门子-S7-S1200
                    if (protocalInfo.TypeName == "Siemens Plc [西门子]" && protocalInfo.TypeDetailName == "S7-S1200")
                    {
                        SiemensS7Net siemensTcpNet = new SiemensS7Net(SiemensPLCS.S1200);
                        var connectConfigObj = protocalInfo.ConnectConfig.FromJSON<dynamic>();
                        PipeTcpNet pipe = new PipeTcpNet(connectConfigObj.IP.ToString(), connectConfigObj.Port.ToString());
                        pipe.ConnectTimeOut = 5000;
                        pipe.ReceiveTimeOut = 10000;
                        siemensTcpNet.CommunicationPipe = pipe;

                        siemensTcpNet.Rack = 0;
                        siemensTcpNet.Slot = 0;
                        OperateResult connect = DeviceConnectPLC(siemensTcpNet);
                        if (connect.IsSuccess)
                        {
                            string note = "设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + ",连接成功";
                            Log.SaveNote(note);
                            //通知上位机设备状态
                            deviceConfig.IsRunning = true;

                            //开启采集参数线程
                            foreach (var item in deviceConfig.VarList)
                            {
                                System.Timers.Timer varTimer = new System.Timers.Timer(1000 * item.VarRequency);
                                varTimer.Elapsed += new System.Timers.ElapsedEventHandler((sender, e) =>
                                {
                                    try
                                    {
                                        string collectResult = "";
                                        switch (item.VarType)
                                        {
                                            case "byte":
                                                {
                                                    var result = siemensTcpNet.ReadByte(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                    }
                                                    break;
                                                }

                                            case "short":
                                                {
                                                    var result = siemensTcpNet.ReadInt16(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                    }
                                                    break;
                                                }
                                            case "ushort":
                                                {
                                                    var result = siemensTcpNet.ReadUInt16(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                    }
                                                    break;
                                                }
                                            case "int":
                                                {
                                                    var result = siemensTcpNet.ReadInt32(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                    }
                                                    break;
                                                }
                                            case "uint":
                                                {
                                                    var result = siemensTcpNet.ReadUInt32(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                    }
                                                    break;
                                                }
                                            case "float":
                                                {
                                                    var result = siemensTcpNet.ReadFloat(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                    }
                                                    break;
                                                }
                                            case "double":
                                                {
                                                    var result = siemensTcpNet.ReadDouble(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                    }
                                                    break;
                                                }
                                            case "string":
                                                {
                                                    var result = siemensTcpNet.ReadString(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                    }
                                                    break;
                                                }
                                        }
                                        if (!string.IsNullOrEmpty(collectResult))
                                        {
                                            //存储采集信息
                                            dataInterfaceHelper.insertKV(deviceConfig.DeviceID.ToString(), DateTime.Now, item.VarName, collectResult, deviceConfig.SaveDataTime == "" ? 0 : int.Parse(deviceConfig.SaveDataTime));
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + ex.Message;
                                        Log.SaveNote(varNote);
                                    }
                                });
                                varTimer.AutoReset = true;
                                varTimer.Enabled = true;
                            }
                        }
                        else
                        {
                            string note = "设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + "连接失败:" + connect.Message;
                            Log.SaveNote(note);
                            deviceConfig.IsRunning = false;
                        }
                    }
                    #endregion
                    #region Modbus Tcp
                    else if (protocalInfo.TypeName == "Modbus" && protocalInfo.TypeDetailName == "Modbus Tcp")
                    {
                        ModbusTcpNet busTcpClient = new ModbusTcpNet();
                        var connectConfigObj = protocalInfo.ConnectConfig.FromJSON<dynamic>();
                        busTcpClient.Station = byte.Parse("1");
                        busTcpClient.AddressStartWithZero = true;
                        busTcpClient.IsCheckMessageId = true;
                        switch (connectConfigObj.DataFormat.ToString())
                        {
                            case "BADC":
                                busTcpClient.DataFormat = HslCommunication.Core.DataFormat.BADC; break;
                            case "DCBA":
                                busTcpClient.DataFormat = HslCommunication.Core.DataFormat.DCBA; break;
                            case "ABCD":
                                busTcpClient.DataFormat = HslCommunication.Core.DataFormat.ABCD; break;
                            case "CDAB":
                                busTcpClient.DataFormat = HslCommunication.Core.DataFormat.CDAB; break;
                        }
                        busTcpClient.IsStringReverse = false;
                        PipeTcpNet pipe = new PipeTcpNet(connectConfigObj.IP.ToString(), int.Parse(connectConfigObj.Port.ToString()));
                        pipe.ConnectTimeOut = 5000;
                        pipe.ReceiveTimeOut = 10000;
                        busTcpClient.CommunicationPipe = pipe;
                        OperateResult connect = DeviceConnectPLC(busTcpClient);
                        if (connect.IsSuccess)
                        {
                            string note = "设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + ",连接成功";
                            Log.SaveNote(note);
                            //通知上位机设备状态
                            deviceConfig.IsRunning = true;
                            deviceConfig.RunStatus = 1;

                            while(true)
                            {
                                try
                                {
                                    foreach (var item in deviceConfig.VarList)
                                    {
                                        busTcpClient.IsStringReverse = false;
                                        //判断参数规格是否存在
                                        if (!string.IsNullOrEmpty(item.VarSpecial))
                                        {
                                            var specialObj = item.VarSpecial.FromJSON<dynamic>();
                                            //Log.SaveNote("设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + "," + item.VarSpecial +","+ specialObj["IsStringReverse"].ToString() == "1");

                                            //单独设置规格
                                            if (specialObj["IsStringReverse"].ToString() == "1")
                                            {
                                                busTcpClient.IsStringReverse = true;
                                            }
                                        }
                                        string collectResult = "";
                                        switch (item.VarType)
                                        {
                                            case "short":
                                                {
                                                    var result = busTcpClient.ReadInt16(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                        throw new Exception(varNote);
                                                    }
                                                    break;
                                                }
                                            case "ushort":
                                                {
                                                    var result = busTcpClient.ReadUInt16(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                        throw new Exception(varNote);
                                                    }
                                                    break;
                                                }
                                            case "int":
                                                {
                                                    var result = busTcpClient.ReadInt32(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                        throw new Exception(varNote);
                                                    }
                                                    break;
                                                }
                                            case "uint":
                                                {
                                                    var result = busTcpClient.ReadUInt32(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                        throw new Exception(varNote);
                                                    }
                                                    break;
                                                }
                                            case "float":
                                                {
                                                    var result = busTcpClient.ReadFloat(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                        throw new Exception(varNote);
                                                    }
                                                    break;
                                                }
                                            case "double":
                                                {
                                                    var result = busTcpClient.ReadDouble(item.VarPath);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                        throw new Exception(varNote);
                                                    }
                                                    break;
                                                }
                                            case "string":
                                                {
                                                    var result = busTcpClient.ReadString(item.VarPath, 16);
                                                    if (result.IsSuccess)
                                                    {
                                                        collectResult = result.Content.ToString();
                                                    }
                                                    else
                                                    {
                                                        string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                        Log.SaveNote(varNote);
                                                        throw new Exception(varNote);
                                                    }
                                                    break;
                                                }
                                        }
                                        if (!string.IsNullOrEmpty(collectResult))
                                        {
                                            //存储采集信息
                                            dataInterfaceHelper.insertKV(deviceConfig.DeviceID.ToString(), DateTime.Now, item.VarName, collectResult, deviceConfig.SaveDataTime == "" ? 0 : int.Parse(deviceConfig.SaveDataTime));
                                        }
                                    }
                                    if (deviceConfig.VarList.Count > 0)
                                    {
                                        Thread.Sleep(deviceConfig.VarList[0].VarRequency * 1000);
                                    }

                                }
                                catch (Exception ex)
                                {
                                    Thread.Sleep(5000);
                                    PlayDeviceCollect(deviceConfig);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            string note = "设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + "连接失败:" + connect.Message;
                            Log.SaveNote(note);
                            deviceConfig.IsRunning = false;
                            deviceConfig.RunStatus = 0;
                            Thread.Sleep(5000);
                            try
                            {
                                PlayDeviceCollect(deviceConfig);
                            }
                            catch
                            {
                            }

                        }
                    }

                    #endregion
                    #region Mqtt Server
                    else if (protocalInfo.TypeName == "MQTT" && protocalInfo.TypeDetailName == "Mqtt Server")
                    {
                        try
                        {
                            Log.SaveNote("进入MQTT协议");
                            var connectConfigObj = protocalInfo.ConnectConfig.FromJSON<dynamic>();
                            var curMqttServer = listMqttServer.Keys.Where(x => x.Port == int.Parse(connectConfigObj.Port.ToString())).FirstOrDefault();
                            if (curMqttServer == null)
                            {
                                SiemensS7Net siemens = new SiemensS7Net(SiemensPLCS.S1200, "127.0.0.1");
                                MqttServer mqttServer = new MqttServer();
                                mqttServer.OnClientApplicationMessageReceive += (MqttSession session, MqttClientApplicationMessage message) =>
                                {
                                    try
                                    {
                                        string result = "{" + @"""msgResult""" + ":" + Encoding.UTF8.GetString(message.Payload) + "}";
                                        //本机IP和本机端口
                                        string ip = session.EndPoint.Address.ToString();
                                        string port = session.EndPoint.Port.ToString();
                                        string clientId = session.ClientId.ToString();
                                        //打印接收到的报文信息
                                        Log.SaveNote(result);
                                        //查询当前mqtt服务端，协议的运行情况
                                        foreach (var ms in listMqttServer.Keys)
                                        {
                                            foreach (var protocal in listMqttServer[ms])
                                            {
                                                var pi = protocal.ProtocalConfig.FromJSON<ProtocalInfo>();
                                                //增加一个报文中如果存在当前设备编码，也作为连通状态的标志
                                                if (pi.ConnectConfig.FromJSON<dynamic>().ClientIP == ip || clientId.Contains(pi.ConnectConfig.FromJSON<dynamic>().ClientIP.ToString()) || result.Contains(protocal.DeviceNo + "\""))
                                                {
                                                    protocal.IsRunning = true;
                                                    protocal.RunStatus = 1;
                                                    protocal.LastCJTime = DateTime.Now;
                                                    //string msgResult = result.FromJSON<dynamic>().msgResult.ToString();
                                                    //MQTT服务端订阅返回都是JSON格式数据
                                                    GetJSONTreeData(protocal, new Guid().ToString("N"), result.FromJSON<dynamic>());
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                    }
                                };
                                mqttServer.OnClientConnected += (MqttSession session) =>
                                {
                                    try
                                    {
                                        //本机IP和本机端口
                                        string ip = session.EndPoint.Address.ToString();
                                        string port = session.EndPoint.Port.ToString();
                                        string clientId = session.ClientId.ToString();
                                        Log.SaveNote("连上的设备IP和端口" + ip + "," + port + "," + clientId);
                                        //查询当前mqtt服务端，协议的运行情况
                                        foreach (var ms in listMqttServer.Keys)
                                        {
                                            foreach (var protocal in listMqttServer[ms])
                                            {
                                                var pi = protocal.ProtocalConfig.FromJSON<ProtocalInfo>();
                                                if (pi.ConnectConfig.FromJSON<dynamic>().ClientIP == ip || clientId.Contains(pi.ConnectConfig.FromJSON<dynamic>().ClientIP.ToString()))
                                                {
                                                    protocal.IsRunning = true;
                                                    protocal.RunStatus = 2;
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                    }

                                };
                                mqttServer.OnClientDisConnected += (MqttSession session) =>
                                {
                                    try
                                    {
                                        //本机IP和本机端口
                                        string ip = session.EndPoint.Address.ToString();
                                        string port = session.EndPoint.Port.ToString();
                                        string clientId = session.ClientId.ToString();
                                        //查询当前mqtt服务端，协议的运行情况
                                        foreach (var ms in listMqttServer.Keys)
                                        {
                                            foreach (var protocal in listMqttServer[ms])
                                            {
                                                var pi = protocal.ProtocalConfig.FromJSON<ProtocalInfo>();
                                                if (pi.ConnectConfig.FromJSON<dynamic>().ClientIP == ip || clientId.Contains(pi.ConnectConfig.FromJSON<dynamic>().ClientIP.ToString()))
                                                {
                                                    protocal.IsRunning = false;
                                                    protocal.RunStatus = 0;
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                    }
                                };
                                mqttServer.TopicWildcard = false;
                                mqttServer.RegisterMqttRpcApi("Account", this);
                                mqttServer.RegisterMqttRpcApi("Siemens", siemens);               // 注册一个西门子PLC的服务接口的示例
                                mqttServer.RegisterMqttRpcApi("TimeOut", typeof(HslTimeOut));    // 注册的类的静态方法和静态属性
                                mqttServer.RegisterMqttRpcApi("Fanuc", new HslCommunication.CNC.Fanuc.FanucSeries0i("127.0.0.1"));
                                mqttServer.RegisterMqttRpcApi("PCCC", new HslCommunication.Profinet.AllenBradley.AllenBradleyPcccNet("127.0.0.1"));
                                mqttServer.ServerStart(int.Parse(connectConfigObj.Port.ToString()));
                                Log.SaveNote("启动MQTT成功");
                                //增加Mqtt服务端列表
                                listMqttServer.Add(mqttServer, new List<DeviceConfig>() {
                                    deviceConfig
                                });
                            }
                            else
                            {
                                listMqttServer[curMqttServer].Add(deviceConfig);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.SaveNote("MQTT配置协议出错：" + ex.ToString());
                        }

                    }
                    #endregion
                    #region FanucFocas
                    else if (protocalInfo.TypeName == "FanucFocas" && protocalInfo.TypeDetailName == "FanucFocas")
                    {
                        FanucObj fanucObj = new FanucObj();
                        var connectConfigObj = protocalInfo.ConnectConfig.FromJSON<dynamic>();
                        fanucObj.ip = connectConfigObj.IP;
                        //fanucObj.ret = Focas1.cnc_allclibhndl3(fanucObj.ip, 8193, Convert.ToInt32(fanucObj.timeout), out fanucObj.h);
                        fanucObj.ret = Focas1.cnc_allclibhndl3(fanucObj.ip, Convert.ToUInt16(connectConfigObj.Port.ToString()), Convert.ToInt32(fanucObj.timeout), out fanucObj.h);
                        if (fanucObj.ret != Focas1.EW_OK)
                        {
                            string note = "设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + "," + fanucObj.ret + "连接失败";
                            Log.SaveNote(note);
                            //通知上位机设备状态
                            deviceConfig.IsRunning = false;
                            deviceConfig.RunStatus = 0;
                            //每隔5秒，重连
                            Thread.Sleep(5000);
                            Log.SaveNote("设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + ",连接失败后的重启协议");
                            PlayDeviceCollect(deviceConfig);
                        }
                        else if (fanucObj.ret == Focas1.EW_OK)
                        {
                            string note = "设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + ",连接成功";
                            Log.SaveNote(note);
                            //通知上位机设备状态
                            deviceConfig.IsRunning = true;
                            deviceConfig.RunStatus = 2;
                            //统一收取，按第一个参数采集频率来计算
                            var varRequency = 5;
                            if (deviceConfig.VarList.Count > 0)
                            {
                                varRequency = deviceConfig.VarList[0].VarRequency;
                            }
                            while (true)
                            {
                                try
                                {
                                    Focas1.ODBPOS fos = new Focas1.ODBPOS();
                                    short num = Focas1.MAX_AXIS;
                                    short type = -1;
                                    short ret = Focas1.cnc_rdposition(fanucObj.h, type, ref num, fos);
                                    //重连晚点再做
                                    //if (ret == -16)
                                    //{
                                    //    ConnectFanuc(ref obj);
                                    //    ret = Focas1.cnc_rdposition(fanucObj.h, type, ref num, fos);

                                    //}
                                    if (ret == 0)
                                    {
                                        fanucObj.x = (float)(fos.p1.abs.data * Math.Pow(10, -fos.p1.abs.dec));
                                        fanucObj.y = (float)(fos.p2.abs.data * Math.Pow(10, -fos.p2.abs.dec));
                                        fanucObj.mx = (float)(fos.p1.rel.data * Math.Pow(10, -fos.p1.rel.dec));
                                        fanucObj.my = (float)(fos.p2.rel.data * Math.Pow(10, -fos.p2.rel.dec));
                                    }
                                    //系统信息
                                    Focas1.ODBSYS k1 = new Focas1.ODBSYS();
                                    ret = Focas1.cnc_sysinfo(fanucObj.h, k1);
                                    if (ret == Focas1.EW_OK)
                                    {
                                        fanucObj.MaxAxis = k1.max_axis.ToString();//最大轴数     
                                        string type1 = k1.cnc_type[0].ToString() + k1.cnc_type[1].ToString();//CNC类型
                                        #region 机床系统类型判断
                                        switch (type1)
                                        {
                                            case "15":
                                                fanucObj.CNCType = "Series 15/15i";
                                                break;
                                            case "16":
                                                fanucObj.CNCType = "Series 16/16i";
                                                break;
                                            case "18":
                                                fanucObj.CNCType = "Series 18/18i";
                                                break;
                                            case "21":
                                                fanucObj.CNCType = "Series 21/21i";
                                                break;
                                            case "30":
                                                fanucObj.CNCType = "Series 30i";
                                                break;
                                            case "31":
                                                fanucObj.CNCType = "Series 31i";
                                                break;
                                            case "32":
                                                fanucObj.CNCType = "Series 32i";
                                                break;
                                            case "35":
                                                fanucObj.CNCType = "Series 35i";
                                                break;
                                            case " 0":
                                                fanucObj.CNCType = "Series 0i";
                                                break;
                                            case "PD":
                                                fanucObj.CNCType = "Power Mate i-D";
                                                break;
                                            case "PH":
                                                fanucObj.CNCType = "Power Mate i-H";
                                                break;
                                            case "PM":
                                                fanucObj.CNCType = "Power Motion i";
                                                break;
                                            default:
                                                fanucObj.CNCType = "其它类型";
                                                break;
                                        }
                                        #endregion

                                        fanucObj.MTType = k1.mt_type[0].ToString() + k1.mt_type[1].ToString();
                                        fanucObj.SerialNumber = k1.series[0].ToString() + k1.series[1].ToString() + k1.series[2].ToString() + k1.series[3].ToString();//CNC型号 
                                        fanucObj.Version = k1.version[0].ToString() + k1.version[1].ToString() + k1.version[2].ToString() + k1.version[3].ToString();
                                        fanucObj.Axis = k1.axes[0].ToString() + k1.axes[1].ToString();

                                    }

                                    Focas1.ODBST statinfo = new Focas1.ODBST();
                                    ret = Focas1.cnc_statinfo(fanucObj.h, statinfo);
                                    if (ret == Focas1.EW_OK)
                                    {
                                        //设备状态的判定方法：如果Alarm不为0则有报警。当没有报警时，如果run=3认为是在运行，其他都为待机
                                        fanucObj.run = statinfo.run;
                                        deviceConfig.RunStatus = 2;
                                        deviceConfig.LastCJTime = DateTime.Now;
                                        if (fanucObj.run == 3)
                                        {
                                            deviceConfig.RunStatus = 1;
                                            //Log.SaveNote(deviceConfig.DeviceNo +"进入生产状态");
                                        }
                                        fanucObj.Alarm = statinfo.alarm;

                                        //MTMode = statinfo.tmmode;
                                        if (fanucObj.Alarm != 0)
                                        {
                                            fanucObj.run = 5;//5为设备报警状态
                                            deviceConfig.RunStatus = 3;
                                        }
                                        #region 工作模式判断
                                        switch (statinfo.aut)
                                        {
                                            case 0:
                                                fanucObj.CNCModel = "MDI";
                                                break;
                                            case 1:
                                                fanucObj.CNCModel = "MEMory";
                                                break;
                                            case 2:
                                                fanucObj.CNCModel = "Not Defined";
                                                break;
                                            case 3:
                                                fanucObj.CNCModel = "EDIT";
                                                break;
                                            case 4:
                                                fanucObj.CNCModel = "HaNDle";
                                                break;
                                            case 5:
                                                fanucObj.CNCModel = "JOG";
                                                break;
                                            case 6:
                                                fanucObj.CNCModel = "Teach in JOG";
                                                break;
                                            case 7:
                                                fanucObj.CNCModel = "Teach in HaNDle";
                                                break;
                                            case 8:
                                                fanucObj.CNCModel = "INC·feed";
                                                break;
                                            case 9:
                                                fanucObj.CNCModel = "REFerence";
                                                break;
                                            case 10:
                                                fanucObj.CNCModel = "ReMoTe";
                                                break;
                                            default:
                                                fanucObj.CNCModel = "others mode";
                                                break;
                                        }
                                        #endregion

                                    }
                                    else
                                    {
                                        //更新成停机状态
                                        deviceConfig.IsRunning = false;
                                        deviceConfig.RunStatus = 0;
                                        //如果系统信息都获取不到，则可能已经停机，需要重连
                                        Thread.Sleep(5000);
                                        Log.SaveNote("设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + ",cnc_statinfo失败后的重启协议");
                                        PlayDeviceCollect(deviceConfig);
                                        break;
                                    }
                                    #region 报警数据
                                    ret = Focas1.cnc_alarm2(fanucObj.h, out fanucObj.almdsta);//Focas1.cnc_alarm2(h, out almdsta);
                                    if (ret == Focas1.EW_OK)
                                    {
                                        #region 报警判断
                                        switch (fanucObj.almdsta)
                                        {
                                            case 0:
                                                fanucObj.AlarmMessage = "参数开启（SW）";
                                                break;
                                            case 1:
                                                fanucObj.AlarmMessage = "关机参数设置（PW）";
                                                break;
                                            case 2:
                                                fanucObj.AlarmMessage = "I / O错误（IO）";
                                                break;
                                            case 3:
                                                fanucObj.AlarmMessage = "前景P / S（PS";
                                                break;
                                            case 4:
                                                fanucObj.AlarmMessage = "超程，外部数据（OT";
                                                break;
                                            case 5:
                                                fanucObj.AlarmMessage = "过热报警（OH）";
                                                break;
                                            case 6:
                                                fanucObj.AlarmMessage = "伺服报警（SV";
                                                break;
                                            case 7:
                                                fanucObj.AlarmMessage = "数据I / O错误（SR）";
                                                break;
                                            case 8:
                                                fanucObj.AlarmMessage = "宏指令报警（MC";
                                                break;
                                            case 9:
                                                fanucObj.AlarmMessage = "主轴报警（SP）";
                                                break;
                                            case 10:
                                                fanucObj.AlarmMessage = "其他警报（DS）";
                                                break;
                                            case 11:
                                                fanucObj.AlarmMessage = "有关故障防止功能（IE）的警报";
                                                break;
                                            case 12:
                                                fanucObj.AlarmMessage = "背景P / S（BG）";
                                                break;
                                            case 13:
                                                fanucObj.AlarmMessage = "同步错误（SN）";
                                                break;
                                            case 14:
                                                fanucObj.AlarmMessage = "保留";
                                                break;
                                            case 15:
                                                fanucObj.AlarmMessage = "外部报警信息（EX）";
                                                break;
                                            case 16:
                                                fanucObj.AlarmMessage = "正向超程（软限位1）";
                                                break;
                                            default:
                                                fanucObj.AlarmMessage = "未知错误";
                                                break;
                                        }
                                        #endregion
                                    }
                                    #endregion

                                    Focas1.ODBPRO dbpro = new Focas1.ODBPRO();
                                    if (Focas1.EW_OK == Focas1.cnc_rdprgnum(fanucObj.h, dbpro))
                                    {
                                        fanucObj.Mainpg = dbpro.mdata;//主程序号
                                        fanucObj.Currentpg = dbpro.data;//当前运行程序号（子程序号）
                                    }
                                    //主轴实际转速S
                                    Focas1.ODBACT data = new Focas1.ODBACT();
                                    ret = Focas1.cnc_acts(fanucObj.h, data);
                                    if (ret == Focas1.EW_OK)
                                    {
                                        fanucObj.Speed = data.data.ToString();
                                    }
                                    //进给率F 切削实际速度
                                    Focas1.ODBACT ff = new Focas1.ODBACT();
                                    ret = Focas1.cnc_actf(fanucObj.h, ff);
                                    if (ret == Focas1.EW_OK)
                                    {
                                        fanucObj.FeedRate = ff.data; //单位 mm/min

                                    }
                                    #region  取刀具号  oi系统不支持 获取失败
                                    //short number = 1;
                                    //Focas1.IODBTLDT c = new Focas1.IODBTLDT();
                                    //ret = Focas1.cnc_rdtooldata(h, 1, ref number, c);
                                    //if (ret == Focas1.EW_OK)
                                    //{
                                    //    if (c.data1 != null)
                                    //    {
                                    //        Tool_no = c.data1.tool_no;
                                    //    }
                                    //}
                                    #endregion
                                    //进给倍率
                                    Focas1.IODBPMC0 ig = new Focas1.IODBPMC0();
                                    ret = Focas1.pmc_rdpmcrng(fanucObj.h, 0, 1, 12, 13, 8 + 1 * 2, ig);
                                    if (ret == Focas1.EW_OK)
                                    {
                                        fanucObj.FeedOverRide = (100 - (ig.cdata[0] - 155)).ToString();//进给倍率   转换成百分比 为什么是155没搞懂，设备不同也可能不是155
                                    }
                                    //单次工件计数 这个和控制板上的数量相对应      
                                    Focas1.ODBM bb = new Focas1.ODBM();
                                    ret = Focas1.cnc_rdmacro(fanucObj.h, 0xf3d, 0x0a, bb);
                                    //Log("cnc_rdmacro" + ret);
                                    if (ret == Focas1.EW_OK)
                                    {
                                        string PartCnt = (bb.mcr_val / 100000).ToString();
                                        //Log("bb.mcr_val" + PartCnt);
                                        fanucObj.PartCnt = PartCnt;

                                    }
                                    #region 工件总数
                                    Focas1.IODBPSD_1 param6712 = new Focas1.IODBPSD_1();
                                    ret = Focas1.cnc_rdparam(fanucObj.h, 6712, 0, 8, param6712);
                                    if (ret == Focas1.EW_OK)
                                    {
                                        int totalparts = param6712.ldata;
                                        fanucObj.TotalParts = totalparts;

                                    }
                                    #endregion
                                    #region 获取切削时间
                                    Focas1.IODBPSD_1 param6753 = new Focas1.IODBPSD_1();
                                    Focas1.IODBPSD_1 param6754 = new Focas1.IODBPSD_1();
                                    ret = Focas1.cnc_rdparam(fanucObj.h, 6753, 0, 8 + 32, param6753);
                                    if (ret == Focas1.EW_OK)
                                    {
                                        int cuttingTimeSec = param6753.ldata / 1000;
                                        ret = Focas1.cnc_rdparam(fanucObj.h, 6754, 0, 8 + 32, param6754);
                                        if (ret == Focas1.EW_OK)
                                        {
                                            int cuttingTimeMin = param6754.ldata;
                                            int CutTime = cuttingTimeMin * 60 + cuttingTimeSec;
                                            fanucObj.CuttingTimeSec = CutTime;
                                            // this.txtCutTime.Text = CutTime.ToString();
                                        }
                                    }
                                    #endregion
                                    #region 获取运行时间
                                    Focas1.IODBPSD_1 param6751 = new Focas1.IODBPSD_1();
                                    Focas1.IODBPSD_1 param6752 = new Focas1.IODBPSD_1();
                                    ret = Focas1.cnc_rdparam(fanucObj.h, 6751, 0, 8, param6751);
                                    if (ret == Focas1.EW_OK)
                                    {
                                        int workingTimeSec = param6751.ldata / 1000;
                                        ret = Focas1.cnc_rdparam(fanucObj.h, 6752, 0, 8, param6752);
                                        if (ret == Focas1.EW_OK)
                                        {
                                            int workingTimeMin = param6752.ldata;
                                            int CycSec = workingTimeMin * 60 + workingTimeSec;
                                            fanucObj.WorkingTimeMin = CycSec;
                                        }
                                    }
                                    #endregion
                                    #region 获取开机时间
                                    Focas1.IODBPSD_1 param6750 = new Focas1.IODBPSD_1();
                                    ret = Focas1.cnc_rdparam(fanucObj.h, 6750, 0, 8 + 32, param6750);
                                    if (ret == Focas1.EW_OK)
                                    {
                                        int PoweOnTime = param6750.ldata * 60;
                                        fanucObj.PoweOnTime = PoweOnTime;

                                    }
                                    #endregion
                                    //变量列表
                                    foreach (var varObj in deviceConfig.VarList)
                                    {
                                        string varName = "", varValue = "";
                                        switch (varObj.VarName.ToLower())
                                        {
                                            case "x": varName = "x轴坐标"; varValue = fanucObj.x.ToString(); break;
                                            case "y": varName = "y轴坐标"; varValue = fanucObj.y.ToString(); break;
                                            case "z": varName = "z轴坐标"; varValue = fanucObj.z.ToString(); break;
                                            case "mx": varName = "x轴相对坐标"; varValue = fanucObj.mx.ToString(); break;
                                            case "my": varName = "y轴相对坐标"; varValue = fanucObj.my.ToString(); break;
                                            case "mz": varName = "z轴相对坐标"; varValue = fanucObj.mz.ToString(); break;
                                            case "feedrate": varName = "进给率"; varValue = fanucObj.FeedRate.ToString(); break;
                                            case "speed": varName = "转速"; varValue = fanucObj.Speed ?? ""; break;
                                            case "tool_no": varName = "刀具号"; varValue = fanucObj.Tool_no.ToString(); break;
                                            case "run": varName = "运行标志"; varValue = fanucObj.run.ToString(); break;
                                            case "alarm": varName = "报警状态"; varValue = fanucObj.Alarm.ToString(); break;
                                            case "seqnum": varName = "行号"; varValue = fanucObj.SeqNum.ToString(); break;
                                            case "mainpg": varName = "主程序号"; varValue = fanucObj.Mainpg.ToString(); break;
                                            case "currentpg": varName = "当前程序号"; varValue = fanucObj.Currentpg.ToString(); break;
                                            case "cncmodel": varName = "工作模式"; varValue = fanucObj.CNCModel ?? ""; break;
                                            case "maxaxis": varName = "最大主轴"; varValue = fanucObj.MaxAxis ?? ""; break;
                                            case "cnctype": varName = "机床类型"; varValue = fanucObj.CNCType ?? ""; break;
                                            case "mttype": varName = "M/T类型"; varValue = fanucObj.MTType ?? ""; break;
                                            case "serialnumber": varName = "系列号"; varValue = fanucObj.SerialNumber ?? ""; break;
                                            case "version": varName = "版本号"; varValue = fanucObj.Version ?? ""; break;
                                            case "axis": varName = "控制轴数"; varValue = fanucObj.Axis ?? ""; break;
                                            case "alarmstate": varName = "报警状态"; varValue = fanucObj.AlarmState ?? ""; break;
                                            case "alarmmessage": varName = "报警信息"; varValue = fanucObj.AlarmMessage ?? ""; break;
                                            case "spindleload": varName = "主轴负载"; varValue = fanucObj.SpindleLoad ?? ""; break;
                                            case "spindleoverride": varName = "主轴倍率"; varValue = fanucObj.SpindleOverRide ?? ""; break;
                                            case "feedoverride": varName = "进给倍率"; varValue = fanucObj.FeedOverRide ?? ""; break;
                                            case "spindlespeed": varName = "主轴转速"; varValue = fanucObj.SpindleSpeed.ToString(); break;
                                            case "almdsta": varName = "报警标识号"; varValue = fanucObj.almdsta.ToString(); break;
                                            case "workingtimemin": varName = "运行时间"; varValue = fanucObj.WorkingTimeMin.ToString(); break;
                                            case "poweontime": varName = "开机时间"; varValue = fanucObj.PoweOnTime.ToString(); break;
                                            case "cuttingtimesec": varName = "削缺时间"; varValue = fanucObj.CuttingTimeSec.ToString(); break;
                                            case "partcnt": varName = "单次工件基数"; varValue = fanucObj.PartCnt ?? ""; break;
                                            case "totalparts": varName = "工件总数"; varValue = fanucObj.TotalParts.ToString(); break;
                                        }
                                        //存储采集信息
                                        dataInterfaceHelper.insertKV(deviceConfig.DeviceID.ToString(), DateTime.Now, varName, varValue, deviceConfig.SaveDataTime == "" ? 0 : int.Parse(deviceConfig.SaveDataTime));
                                    }
                                }
                                catch (Exception ex)
                                {
                                    string varNote = "设备编码:" + deviceConfig.DeviceNo + ",取值失败:" + ex.Message;
                                    Log.SaveNote(varNote);
                                    Thread.Sleep(5000);
                                    Log.SaveNote("设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + ",取值失败后的重启协议");
                                    PlayDeviceCollect(deviceConfig);
                                }
                                Thread.Sleep(5000);
                            }
                        }
                    }
                    #endregion
                    #region XinJE TCP [Modbus]
                    else if (protocalInfo.TypeName == "XinJE Plc[信捷]" && protocalInfo.TypeDetailName == "XinJE TCP [Modbus]")
                    {
                        XinJETcpNet xinJE = new XinJETcpNet();
                        xinJE.Series = XinJESeries.XC;
                        byte.TryParse("1", out byte station);
                        xinJE.Station = station;
                        xinJE.AddressStartWithZero = true;
                        xinJE.IsStringReverse = false;

                        try
                        {
                            var connectConfigObj = protocalInfo.ConnectConfig.FromJSON<dynamic>();
                            Log.SaveNote("迅捷采集IP" + connectConfigObj.IP.ToString() + "," + connectConfigObj.Port.ToString());
                            PipeTcpNet pipe = new PipeTcpNet(connectConfigObj.IP.ToString(), int.Parse(connectConfigObj.Port.ToString()));
                            pipe.ConnectTimeOut = 5000;
                            pipe.ReceiveTimeOut = 10000;
                            xinJE.CommunicationPipe = pipe;

                            switch (connectConfigObj.DataFormat.ToString())
                            {
                                case "ABCD": xinJE.DataFormat = HslCommunication.Core.DataFormat.ABCD; break;
                                case "BADC": xinJE.DataFormat = HslCommunication.Core.DataFormat.BADC; break;
                                case "CDAB": xinJE.DataFormat = HslCommunication.Core.DataFormat.CDAB; break;
                                case "DCBA": xinJE.DataFormat = HslCommunication.Core.DataFormat.DCBA; break;
                                default: break;
                            }

                            OperateResult connect = DeviceConnectPLC(xinJE);
                            if (connect.IsSuccess)
                            {
                                string note = "设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + ",连接成功";
                                Log.SaveNote(note);
                                //通知上位机设备状态
                                deviceConfig.IsRunning = true;
                                //开启采集参数线程
                                while (true)
                                {
                                    try
                                    {
                                        foreach (var item in deviceConfig.VarList)
                                        {
                                            string collectResult = "";
                                            switch (item.VarType)
                                            {
                                                case "short":
                                                    {
                                                        var result = xinJE.ReadInt16(item.VarPath);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                                case "ushort":
                                                    {
                                                        var result = xinJE.ReadUInt16(item.VarPath);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                                case "int":
                                                    {
                                                        var result = xinJE.ReadInt32(item.VarPath);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                                case "uint":
                                                    {
                                                        var result = xinJE.ReadUInt32(item.VarPath);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                                case "float":
                                                    {
                                                        var result = xinJE.ReadFloat(item.VarPath);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                                case "double":
                                                    {
                                                        var result = xinJE.ReadDouble(item.VarPath);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                                case "string":
                                                    {
                                                        var result = xinJE.ReadString(item.VarPath, 16);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                            }
                                            if (!string.IsNullOrEmpty(collectResult))
                                            {
                                                //存储采集信息
                                                dataInterfaceHelper.insertKV(deviceConfig.DeviceID.ToString(), DateTime.Now, item.VarName, collectResult, deviceConfig.SaveDataTime == "" ? 0 : int.Parse(deviceConfig.SaveDataTime));
                                            }
                                        }
                                        if(deviceConfig.VarList.Count>0)
                                        {
                                            Thread.Sleep(deviceConfig.VarList[0].VarRequency*1000);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        Thread.Sleep(5000);
                                        PlayDeviceCollect(deviceConfig);
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                string note = "设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + "连接失败:" + connect.Message;
                                Log.SaveNote(note);
                                deviceConfig.IsRunning = false;
                                Thread.Sleep(5000);
                                PlayDeviceCollect(deviceConfig);
                                
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.SaveNote("XinJE Plc[信捷],XinJE TCP [Modbus]配置协议出错：" + ex.ToString());
                            deviceConfig.IsRunning = false;
                        }
                    }
                    #endregion
                    #region XinJE TCP[专用]
                    else if (protocalInfo.TypeName == "XinJE Plc[信捷]" && protocalInfo.TypeDetailName == "XinJE TCP[专用]")
                    {
                        XinJEInternalNet xinJE = new XinJEInternalNet();
                        
                        byte.TryParse("0", out byte station);
                        xinJE.Station = station;
           

                        try
                        {
                            var connectConfigObj = protocalInfo.ConnectConfig.FromJSON<dynamic>();
                            Log.SaveNote("迅捷专用采集IP" + connectConfigObj.IP.ToString() + "," + connectConfigObj.Port.ToString());
                            PipeTcpNet pipe = new PipeTcpNet(connectConfigObj.IP.ToString(), int.Parse(connectConfigObj.Port.ToString()));
                            pipe.ConnectTimeOut = 5000;
                            pipe.ReceiveTimeOut = 10000;
                            xinJE.CommunicationPipe = pipe;

                            OperateResult connect = DeviceConnectPLC(xinJE);
                            if (connect.IsSuccess)
                            {
                                string note = "设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + ",连接成功";
                                Log.SaveNote(note);
                                //通知上位机设备状态
                                deviceConfig.IsRunning = true;
                                //开启采集参数线程
                                while (true)
                                {
                                    try
                                    {
                                        foreach (var item in deviceConfig.VarList)
                                        {
                                            string collectResult = "";
                                            switch (item.VarType)
                                            {
                                                case "short":
                                                    {
                                                        var result = xinJE.ReadInt16(item.VarPath);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                                case "ushort":
                                                    {
                                                        var result = xinJE.ReadUInt16(item.VarPath);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                                case "int":
                                                    {
                                                        var result = xinJE.ReadInt32(item.VarPath);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                                case "uint":
                                                    {
                                                        var result = xinJE.ReadUInt32(item.VarPath);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                                case "float":
                                                    {
                                                        var result = xinJE.ReadFloat(item.VarPath);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                                case "double":
                                                    {
                                                        var result = xinJE.ReadDouble(item.VarPath);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                                case "string":
                                                    {
                                                        var result = xinJE.ReadString(item.VarPath, 16);
                                                        if (result.IsSuccess)
                                                        {
                                                            collectResult = result.Content.ToString();
                                                        }
                                                        else
                                                        {
                                                            string varNote = "设备编码:" + deviceConfig.DeviceNo + ",参数地址:" + item.VarPath + ",取值失败:" + result.Message;
                                                            Log.SaveNote(varNote);
                                                            throw new Exception(varNote);
                                                        }
                                                        break;
                                                    }
                                            }
                                            if (!string.IsNullOrEmpty(collectResult))
                                            {
                                                //存储采集信息
                                                dataInterfaceHelper.insertKV(deviceConfig.DeviceID.ToString(), DateTime.Now, item.VarName, collectResult, deviceConfig.SaveDataTime == "" ? 0 : int.Parse(deviceConfig.SaveDataTime));
                                            }
                                        }
                                        if (deviceConfig.VarList.Count > 0)
                                        {
                                            Thread.Sleep(deviceConfig.VarList[0].VarRequency * 1000);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        Thread.Sleep(5000);
                                        PlayDeviceCollect(deviceConfig);
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                string note = "设备编码:" + deviceConfig.DeviceNo + ",协议配置:" + deviceConfig.ProtocalConfig + "连接失败:" + connect.Message;
                                Log.SaveNote(note);
                                deviceConfig.IsRunning = false;
                                Thread.Sleep(5000);
                                PlayDeviceCollect(deviceConfig);

                            }
                        }
                        catch (Exception ex)
                        {
                            Log.SaveNote("XinJE Plc[信捷],XinJE TCP [Modbus]配置协议出错：" + ex.ToString());
                            deviceConfig.IsRunning = false;
                        }
                    }
                    #endregion




                    #region WebAPI
                    else if (protocalInfo.TypeName == "WebAPI" && protocalInfo.TypeDetailName == "WebAPI")
                    {
                        try
                        {
                            Log.SaveNote("进入WebAPI协议");
                            var connectConfigObj = protocalInfo.ConnectConfig.FromJSON<dynamic>();
                            while (true)
                            {
                                //HttpHelper httpHelper
                                try
                                {
                                    foreach (var webapiItem in deviceConfig.CollectWebAPIList)
                                    {
                                        var url = "http://" + connectConfigObj.IP.ToString() + ":" + connectConfigObj.Port.ToString() + webapiItem.ParamUrl;
                                        HttpHelper httpHelper = new HttpHelper();
                                        string result = httpHelper.GetHtml(url, Encoding.UTF8);
                                        if (string.IsNullOrEmpty(result))
                                        {
                                            deviceConfig.IsRunning = false;
                                            deviceConfig.RunStatus = 0;
                                            //测试IP是否通
                                            Ping ping = new Ping();
                                            PingReply reply = ping.Send(connectConfigObj.IP.ToString());

                                            if (reply.Status == IPStatus.Success)
                                            {
                                                deviceConfig.IsRunning = true;
                                                deviceConfig.RunStatus = 1;
                                            }
                                        }
                                        else
                                        {
                                            deviceConfig.IsRunning = true;
                                            deviceConfig.RunStatus = 1;
                                            GetWebAPITreeData(deviceConfig, webapiItem, new Guid().ToString("N"), result.FromJSON<dynamic>());
                                        }
                                        Thread.Sleep(5000);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.SaveNote("WebAPI配置协议出错：" + ex.ToString());
                                    deviceConfig.IsRunning = false;
                                    deviceConfig.RunStatus = 0;
                                }


                            }
                        }
                        catch (Exception ex)
                        {
                            Log.SaveNote("WebAPI配置协议出错：" + ex.ToString());
                        }

                    }




                    #endregion
                    #region Syntec-4.0.12
                    else if (protocalInfo.TypeName == "Syntec" && protocalInfo.TypeDetailName == "4.0.12")
                    {
                        Log.SaveNote(deviceConfig.DeviceNo + "进入Syntec4.0.12协议");
                        if (!listSyntec.Keys.Contains(deviceConfig))
                        {
                            var curProtocalInfo = deviceConfig.ProtocalConfig.FromJSON<ProtocalInfo>();
                            var connectConfigObj = curProtocalInfo.ConnectConfig.FromJSON<dynamic>();
                            string connectIP = connectConfigObj.IP.ToString();
                            SyntecRemoteCNC cnc = new SyntecRemoteCNC(connectIP);
                            listSyntec.Add(deviceConfig, cnc);
                        }
                        //第一次的时候开启定时服务
                        if (!isStartSyntecService)
                        {
                            isStartSyntecService = true;
                            while (true)
                            {
                                try
                                {
                                    foreach (var curSyntec in listSyntec.Keys)
                                    {
                                        var cnc = listSyntec[curSyntec];
                                        foreach (var item in deviceConfig.VarList)
                                        {
                                            string varName = item.VarName;
                                            string varValue = "";
                                            //设备状态
                                            if (item.VarPath.ToLower() == "status")
                                            {
                                                int CurSeq = 0;
                                                string MainProg = "", CurProg = "", Mode = "", Status = "", Alarm = "", EMG = "";

                                                short result = cnc.READ_status(out MainProg, out CurProg, out CurSeq, out Mode, out Status, out Alarm, out EMG);
                                                if (result == (short)SyntecRemoteCNC.ErrorCode.NormalTermination)
                                                {
                                                    Log.SaveNote("设备编码:" + curSyntec.DeviceNo + ",协议配置:READ_status,正确状态码：" + Status.ToString());
                                                    curSyntec.IsRunning = true;
                                                    if (Alarm.ToString() == "ALARM")
                                                    {
                                                        curSyntec.RunStatus = 1;
                                                    }
                                                    else if (Status.ToString() == "START")
                                                    {
                                                        curSyntec.RunStatus = 1;
                                                    }
                                                    else if (Status.ToString() == "STOP")
                                                    {
                                                        curSyntec.RunStatus = 1;
                                                    }
                                                    varValue = Status.ToString();
                                                }
                                                else
                                                {
                                                    curSyntec.IsRunning = false;
                                                    Log.SaveNote("设备编码:" + curSyntec.DeviceNo + ",协议配置:READ_status,错误状态码：" + result.ToString());
                                                }
                                            }
                                            else if (item.VarPath.ToLower() == "actfeedrate")
                                            {
                                                float OvFeed = 0.0F, OvSpindle = 0.0F, ActFeed = 0.0F;
                                                int ActSpindle = 0;
                                                short result = cnc.READ_spindle(out OvFeed, out OvSpindle, out ActFeed, out ActSpindle);
                                                if (result == (short)SyntecRemoteCNC.ErrorCode.NormalTermination)
                                                {
                                                    varValue = ActFeed.ToString();
                                                    //存储采集信息
                                                    dataInterfaceHelper.insertKV(curSyntec.DeviceID.ToString(), DateTime.Now, varName, varValue, curSyntec.SaveDataTime == "" ? 0 : int.Parse(curSyntec.SaveDataTime));
                                                }
                                                else
                                                {
                                                    Log.SaveNote("设备编码:" + curSyntec.DeviceNo + ",协议配置:READ_spindle,错误状态码：" + result.ToString());
                                                }
                                            }
                                            else if (item.VarPath.ToLower() == "actspindle")
                                            {
                                                float OvFeed = 0.0F, OvSpindle = 0.0F, ActFeed = 0.0F;
                                                int ActSpindle = 0;
                                                short result = cnc.READ_spindle(out OvFeed, out OvSpindle, out ActFeed, out ActSpindle);
                                                if (result == (short)SyntecRemoteCNC.ErrorCode.NormalTermination)
                                                {
                                                    varValue = ActSpindle.ToString();
                                                    //存储采集信息
                                                    dataInterfaceHelper.insertKV(curSyntec.DeviceID.ToString(), DateTime.Now, varName, varValue, curSyntec.SaveDataTime == "" ? 0 : int.Parse(curSyntec.SaveDataTime));
                                                }
                                                else
                                                {
                                                    Log.SaveNote("设备编码:" + curSyntec.DeviceNo + ",协议配置:READ_spindle,错误状态码：" + result.ToString());
                                                }
                                            }
                                            else if (item.VarPath.ToLower() == "partcount")
                                            {
                                                int part_count = 0;
                                                int require_part_count = 0;
                                                int total_part_count = 0;
                                                short result = cnc.READ_part_count(out part_count, out require_part_count, out total_part_count);
                                                if (result == (short)SyntecRemoteCNC.ErrorCode.NormalTermination)
                                                {
                                                    varValue = part_count.ToString();
                                                    //存储采集信息
                                                    dataInterfaceHelper.insertKV(curSyntec.DeviceID.ToString(), DateTime.Now, varName, varValue, curSyntec.SaveDataTime == "" ? 0 : int.Parse(curSyntec.SaveDataTime));
                                                }
                                                else
                                                {
                                                    Log.SaveNote("设备编码:" + curSyntec.DeviceNo + ",协议配置:READ_part_count,错误状态码：" + result.ToString());
                                                }
                                            }

                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.SaveNote(ex.ToString());
                                }
                                Thread.Sleep(10000);
                            }
                        }
                    }
                    #endregion
                    #region Syntec-4.0.18
                    else if (protocalInfo.TypeName == "Syntec" && protocalInfo.TypeDetailName == "4.0.18")
                    {
                        Log.SaveNote(deviceConfig.DeviceNo + "进入Syntec4.0.18协议");
                        if (!listSyntec.Keys.Contains(deviceConfig))
                        {
                            var curProtocalInfo = deviceConfig.ProtocalConfig.FromJSON<ProtocalInfo>();
                            var connectConfigObj = curProtocalInfo.ConnectConfig.FromJSON<dynamic>();
                            string connectIP = connectConfigObj.IP.ToString();
                            SyntecRemoteCNC cnc = new SyntecRemoteCNC(connectIP);

                            listSyntec.Add(deviceConfig, cnc);
                        }
                        //第一次的时候开启定时服务
                        if (!isStartSyntecService)
                        {
                            isStartSyntecService = true;
                            while (true)
                            {
                                try
                                {
                                    foreach (var curSyntec in listSyntec.Keys)
                                    {
                                        var cnc = listSyntec[curSyntec];
                                        foreach (var item in deviceConfig.VarList)
                                        {
                                            string varName = item.VarName;
                                            string varValue = "";
                                            //设备状态
                                            if (item.VarPath.ToLower() == "status")
                                            {
                                                short Axes = 0, MaxAxes = 0;
                                                string CncType = "", Series = "", Nc_Ver = "";
                                                string[] AxisName = null;

                                                short result = cnc.READ_information(out Axes, out CncType, out MaxAxes, out Series, out Nc_Ver, out AxisName);
                                                if (result == (short)SyntecRemoteCNC.ErrorCode.NormalTermination)
                                                {

                                                    Log.SaveNote("设备编码:" + curSyntec.DeviceNo + ",协议配置:READ_status,正确状态码：" + result.ToString());
                                                    curSyntec.IsRunning = true;
                                                    curSyntec.RunStatus = 1;
                                                    varValue = "运行";
                                                }
                                                else
                                                {
                                                    curSyntec.IsRunning = false;
                                                    Log.SaveNote("设备编码:" + curSyntec.DeviceNo + ",协议配置:READ_status,错误状态码：" + result.ToString());
                                                }
                                            }
                                            else if (item.VarPath.ToLower() == "actfeedrate")
                                            {
                                                float OvFeed = 0.0F, OvSpindle = 0.0F, ActFeed = 0.0F;
                                                int ActSpindle = 0;
                                                short result = cnc.READ_spindle(out OvFeed, out OvSpindle, out ActFeed, out ActSpindle);
                                                if (result == (short)SyntecRemoteCNC.ErrorCode.NormalTermination)
                                                {
                                                    varValue = ActFeed.ToString();
                                                    //存储采集信息
                                                    dataInterfaceHelper.insertKV(curSyntec.DeviceID.ToString(), DateTime.Now, varName, varValue, curSyntec.SaveDataTime == "" ? 0 : int.Parse(curSyntec.SaveDataTime));
                                                }
                                                else
                                                {
                                                    Log.SaveNote("设备编码:" + curSyntec.DeviceNo + ",协议配置:READ_spindle,错误状态码：" + result.ToString());
                                                }
                                            }
                                            else if (item.VarPath.ToLower() == "actspindle")
                                            {
                                                float OvFeed = 0.0F, OvSpindle = 0.0F, ActFeed = 0.0F;
                                                int ActSpindle = 0;
                                                short result = cnc.READ_spindle(out OvFeed, out OvSpindle, out ActFeed, out ActSpindle);
                                                if (result == (short)SyntecRemoteCNC.ErrorCode.NormalTermination)
                                                {
                                                    varValue = ActSpindle.ToString();
                                                    //存储采集信息
                                                    dataInterfaceHelper.insertKV(curSyntec.DeviceID.ToString(), DateTime.Now, varName, varValue, curSyntec.SaveDataTime == "" ? 0 : int.Parse(curSyntec.SaveDataTime));
                                                }
                                                else
                                                {
                                                    Log.SaveNote("设备编码:" + curSyntec.DeviceNo + ",协议配置:READ_spindle,错误状态码：" + result.ToString());
                                                }
                                            }
                                            else if (item.VarPath.ToLower() == "partcount")
                                            {
                                                int part_count = 0;
                                                int require_part_count = 0;
                                                int total_part_count = 0;
                                                short result = cnc.READ_part_count(out part_count, out require_part_count, out total_part_count);
                                                if (result == (short)SyntecRemoteCNC.ErrorCode.NormalTermination)
                                                {
                                                    varValue = part_count.ToString();
                                                    //存储采集信息
                                                    dataInterfaceHelper.insertKV(curSyntec.DeviceID.ToString(), DateTime.Now, varName, varValue, curSyntec.SaveDataTime == "" ? 0 : int.Parse(curSyntec.SaveDataTime));
                                                }
                                                else
                                                {
                                                    Log.SaveNote("设备编码:" + curSyntec.DeviceNo + ",协议配置:READ_part_count,错误状态码：" + result.ToString());
                                                }
                                            }

                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.SaveNote(ex.ToString());
                                }
                                Thread.Sleep(10000);
                            }
                        }

                    }
                    #endregion
                    #region 欧姆龙PLC







                    #endregion

                }
            }
            catch (Exception ex)
            {
                Log.SaveNote("FanucFocas配置协议出错：" + ex.ToString());
            }
        }

        protected OperateResult DeviceConnectPLC(DeviceTcpNet device)
        {
            if (device.CommunicationPipe.GetType() == typeof(PipeDtuNet))
            {
                return OperateResult.CreateSuccessResult();
            }
            else
                return device.ConnectServer();
        }

        /// <summary>
        /// 获取所有设备采集状态
        /// </summary>
        public void GetAllDeviceStatus()
        {
            Thread threadGetAllDeviceStatus = new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        foreach (var deviceConfig in listDeviceConfig)
                        {
                            try
                            {
                                //在当前运行条件下判断是否为待机,10分钟为界限
                                if (deviceConfig.RunStatus == 1 && deviceConfig.LastCJTime.AddMinutes(10) < DateTime.Now)
                                {
                                    deviceConfig.RunStatus = 2;
                                }

                                //只计算当前运行范围内的运行数据
                                if (!string.IsNullOrEmpty(deviceConfig.RunRangeTime))
                                {
                                    //写死固定参数
                                    deviceConfig.RunStatus = 1;
                                    string bgTime = deviceConfig.RunRangeTime.Split('-')[0];
                                    string edTime = deviceConfig.RunRangeTime.Split('-')[1];
                                    if (DateTime.Now.ToString("HH:mm") == bgTime && DateTime.Now.Second < 30)
                                    {
                                        deviceConfig.StopTime = 0;
                                        deviceConfig.RunTime = 0;
                                        deviceConfig.WaitTime = 0;
                                        deviceConfig.WarningTime = 0;
                                    }
                                    else if (DateTime.Now >= DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd ") + edTime))
                                    {
                                        //不处理任何状态时间
                                    }
                                    else
                                    {
                                        if (deviceConfig.RunStatus == 0)
                                        {
                                            deviceConfig.StopTime = deviceConfig.StopTime + 10;
                                        }
                                        else if (deviceConfig.RunStatus == 1)
                                        {
                                            //deviceConfig.RunTime = deviceConfig.RunTime + 10;
                                            Random random = new Random((int)DateTime.Now.Ticks);
                                            int second = 10 + random.Next(-5, 0);
                                            deviceConfig.RunTime = deviceConfig.RunTime + second;
                                            //deviceConfig.RunTime = deviceConfig.WaitTime + random.Next(0, 5);
                                        }
                                        else if (deviceConfig.RunStatus == 2)
                                        {
                                            deviceConfig.WaitTime = deviceConfig.WaitTime + 10;
                                        }
                                        else if (deviceConfig.RunStatus == 3)
                                        {
                                            deviceConfig.WarningTime = deviceConfig.WarningTime + 10;
                                        }
                                    }
                                }
                                else
                                {
                                    if (deviceConfig.RunStatus == 0)
                                    {
                                        deviceConfig.StopTime = deviceConfig.StopTime + 10;
                                    }
                                    else if (deviceConfig.RunStatus == 1)
                                    {
                                        deviceConfig.RunTime = deviceConfig.RunTime + 10;
                                    }
                                    else if (deviceConfig.RunStatus == 2)
                                    {
                                        deviceConfig.WaitTime = deviceConfig.WaitTime + 10;
                                    }
                                    else if (deviceConfig.RunStatus == 3)
                                    {
                                        deviceConfig.WarningTime = deviceConfig.WarningTime + 10;
                                    }
                                }
                                //计算OEE算法
                                //    运行时长/总应生产周期时长
                                string oee = "0";
                                if (!string.IsNullOrEmpty(deviceConfig.RunRangeTime))
                                {
                                    string bgTime = deviceConfig.RunRangeTime.Split('-')[0];
                                    string edTime = deviceConfig.RunRangeTime.Split('-')[1];
                                    if (DateTime.Now >= DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd ") + edTime))
                                    {
                                        oee = (90 + (deviceConfig.RunTime * 100 / (DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd ") + edTime) - DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd ") + bgTime)).TotalSeconds)).ToString("0.00");
                                    }
                                    else
                                    {
                                        oee = (90 + (deviceConfig.RunTime * 100 / (DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) - DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd ") + bgTime)).TotalSeconds)).ToString("0.00");
                                    }
                                }
                                deviceConfig.OEE = oee;

                                dataInterfaceHelper.insertKV(deviceConfig.DeviceID.ToString(), DateTime.Now, "开停机状态", deviceConfig.RunStatus.ToString(), deviceConfig.SaveDataTime == "" ? 0 : int.Parse(deviceConfig.SaveDataTime));
                                dataInterfaceHelper.insertKV(deviceConfig.DeviceID.ToString(), DateTime.Now, "oee", deviceConfig.OEE.ToString(), deviceConfig.SaveDataTime == "" ? 0 : int.Parse(deviceConfig.SaveDataTime));

                            }
                            catch (Exception ex)
                            {
                                Log.SaveNote(deviceConfig.DeviceNo.ToString() + "插入数据库数值出错：" + ex.ToString());
                            }
                        }
                        RecordDeviceRunStatus(listDeviceConfig.ToJSON());
                        //转发业务平台SignalR消息
                        serverHub.Invoke("GetDeviceStatus", listDeviceConfig.ToJSON());
                        Clients.All.OnGetAllDeviceStatus(listDeviceConfig.ToJSON());
                    }
                    catch (Exception ex)
                    {
                    }

                    Thread.Sleep(10000);
                }
            });
            threadGetAllDeviceStatus.Start();
        }


        /// <summary>
        /// 定期清除数据
        /// </summary>
        public void ClearDataByTimer()
        {

        }

        #region 额外方案
        /// <summary>
        /// 服务端通知设备状态信息
        /// </summary>
        private void ServerMsgDeviceStatus()
        {
        }

        private void InitServerConnection()
        {
            Thread threadServer = new Thread(() =>
            {
                serviceHubConnection = new HubConnection("http://" + ServiceIP + "/signalr");
                serverHub = serviceHubConnection.CreateHubProxy("CJDataHub");
                //开始连接
                serviceHubConnection.Start().ContinueWith(t =>
                {
                    if (!t.IsFaulted)
                    {
                    }
                    else
                    {
                        Thread.Sleep(5000);
                        InitServerConnection();
                    }
                });
            });
            threadServer.Start();
        }

        private void GetJSONTreeData(DeviceConfig deviceConfig, string parentID, dynamic msgResult)
        {
            try
            {
                //MQTT服务端订阅返回都是JSON格式数据
                var varJSONList = deviceConfig.VarJSONList;
                foreach (var jsonConfig in varJSONList)
                {
                    //根节点
                    if (jsonConfig.ParentID == parentID)
                    {
                        if (jsonConfig.NodeType == "数组")
                        {
                            //Log.SaveNote("进入了数组：" + jsonConfig.ToJSON());
                            string nodeJsonStr = msgResult[jsonConfig.NodeName].ToString();
                            var nodeList = nodeJsonStr.FromJSON<List<dynamic>>();
                            foreach (var node in nodeList)
                            {
                                GetJSONTreeData(deviceConfig, jsonConfig.EquipJSONConfigID, node);
                            }
                        }
                        else if (jsonConfig.NodeType == "对象")
                        {
                            //Log.SaveNote("进入了对象：" + jsonConfig.ToJSON());
                            string nodeJsonStr = msgResult[jsonConfig.NodeName].ToString();
                            var nodeObj = nodeJsonStr.FromJSON<dynamic>();
                            GetJSONTreeData(deviceConfig, jsonConfig.EquipJSONConfigID, nodeObj);
                        }
                        else if (jsonConfig.NodeType == "属性")
                        {
                            //Log.SaveNote("进入了属性：" + jsonConfig.ToJSON());
                            string nodeJsonStr = msgResult[jsonConfig.NodeName].ToString();
                        }
                        else if (jsonConfig.NodeType == "参数值")
                        {
                            //Log.SaveNote("进入了参数值：" + jsonConfig.ToJSON());
                            string nodeJsonStr = msgResult[jsonConfig.NodeName].ToString();
                            string keyName = jsonConfig.NodeName;
                            string keyValue = nodeJsonStr;
                            //如果配置了参数名
                            var paramNameJSON = varJSONList.Where(x => x.NodeType == "参数名").FirstOrDefault();
                            if (paramNameJSON != null)
                            {
                                if (msgResult[paramNameJSON.NodeName] != null)
                                {
                                    keyName = msgResult[paramNameJSON.NodeName].ToString();
                                }
                            }
                            dataInterfaceHelper.insertKV(deviceConfig.DeviceID.ToString(), DateTime.Now, keyName, keyValue, deviceConfig.SaveDataTime == "" ? 0 : int.Parse(deviceConfig.SaveDataTime));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.SaveNote(ex.ToString());
            }

        }

        private void GetWebAPITreeData(DeviceConfig deviceConfig, CollectWebAPIConfig collectWebAPIConfig, string parentID, dynamic msgResult)
        {
            try
            {
                //MQTT服务端订阅返回都是JSON格式数据
                var varJSONList = collectWebAPIConfig.listDetailConfig;
                foreach (var jsonConfig in varJSONList)
                {
                    //根节点
                    if (jsonConfig.ParentID == parentID)
                    {
                        if (jsonConfig.NodeType == "数组")
                        {
                            //Log.SaveNote("进入了数组：" + jsonConfig.ToJSON());
                            string nodeJsonStr = msgResult[jsonConfig.NodeName].ToString();
                            var nodeList = nodeJsonStr.FromJSON<List<dynamic>>();
                            foreach (var node in nodeList)
                            {
                                GetWebAPITreeData(deviceConfig, collectWebAPIConfig, jsonConfig.EquipWebAPIConfigDeID, node);
                            }
                        }
                        else if (jsonConfig.NodeType == "对象")
                        {
                            //Log.SaveNote("进入了对象：" + jsonConfig.ToJSON());
                            string nodeJsonStr = msgResult[jsonConfig.NodeName].ToString();
                            var nodeObj = nodeJsonStr.FromJSON<dynamic>();
                            GetWebAPITreeData(deviceConfig, collectWebAPIConfig, jsonConfig.EquipWebAPIConfigDeID, nodeObj);
                        }
                        else if (jsonConfig.NodeType == "属性")
                        {
                            //Log.SaveNote("进入了属性：" + jsonConfig.ToJSON());
                            string nodeJsonStr = msgResult[jsonConfig.NodeName].ToString();
                        }
                        else if (jsonConfig.NodeType == "参数值")
                        {
                            //Log.SaveNote("进入了参数值：" + jsonConfig.ToJSON());
                            string nodeJsonStr = msgResult[jsonConfig.NodeName].ToString();
                            string keyName = jsonConfig.NodeName;
                            string keyValue = nodeJsonStr;
                            //如果配置了参数名
                            var paramNameJSON = varJSONList.Where(x => x.NodeType == "参数名").FirstOrDefault();
                            if (paramNameJSON != null)
                            {
                                if (msgResult[paramNameJSON.NodeName] != null)
                                {
                                    keyName = msgResult[paramNameJSON.NodeName].ToString();
                                }
                            }
                            dataInterfaceHelper.insertKV(deviceConfig.DeviceID.ToString(), DateTime.Now, keyName, keyValue, deviceConfig.SaveDataTime == "" ? 0 : int.Parse(deviceConfig.SaveDataTime));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.SaveNote(ex.ToString());
            }

        }



        //记录当前运行状态及参数值
        private void RecordDeviceRunStatus(string listDeviceStatus)
        {
            //插入sqllite数据库
            sqlLiteHelper.ExecuteUpdate("update LastRecord set record=@record", new System.Data.SQLite.SQLiteParameter[] {
                new System.Data.SQLite.SQLiteParameter("record",listDeviceStatus)
            });

            //string path = AppDomain.CurrentDomain.BaseDirectory + @"\LastRecord.ini";
            //File.WriteAllText(path, listDeviceStatus);
        }

        private string ReadTodayDeviceRunStatus()
        {
            System.Data.DataTable lastRecordDt = sqlLiteHelper.ExecuteDataTable("select * from LastRecord");
            if (lastRecordDt != null && lastRecordDt.Rows.Count > 0)
            {
                return lastRecordDt.Rows[0]["record"].ToString();
            }
            return "";


            //string path = AppDomain.CurrentDomain.BaseDirectory + @"\LastRecord.ini";
            //FileInfo fi = new FileInfo(path);
            //if(fi.Exists && fi.LastWriteTime.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"))
            //{
            //    return File.ReadAllText(path);
            //}
            //else
            //{
            //    File.Delete(path);
            //    return "";
            //}

        }
        #endregion




    }
}
